package com.mc.developmentkit.activitys;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qamaster.android.R;
import com.mc.developmentkit.bean.AboutUsInfo;
import com.mc.developmentkit.utils.Primary;
import com.mc.developmentkit.config.MCConstant;
import com.mc.developmentkit.config.MCThird;
import com.mc.developmentkit.https.HttpUtils;
import com.mc.developmentkit.json.Json;
import com.mc.developmentkit.login.MCThirdPartyLogin;
import com.mc.developmentkit.utils.Autjcode;
import com.mc.developmentkit.utils.MCUtils;
import com.mc.developmentkit.utils.ToastUtil;
import com.mc.developmentkit.views.TitleManger;

import org.json.JSONObject;

/**
 * Created by LeBron on 2016/12/28.
 */

public class RegisterActivity extends Activity implements View.OnClickListener {


    private RadioGroup radioGroup;
    private RadioButton radioButton_phoneRegister, radioButton_AccountRegister;
    private EditText et_RegisterAccount, getEt_RegisterPassword, et_Code;
    private TextView tv_GetPhoneCode, tv_QunNum, tv_appText, tv_WangZhi, tv_XieYi, tv_toLogin;
    private ImageView img_GetSuiJiCode, login_WeChat, login_QQ, join_QQqun;
    private Button btn_Register;
    private CheckBox checkBox;
    private String code_resh; //验证码
    private String register_Account;
    private String register_Password;
    private String register_Code;
    private AboutUsInfo aboutUs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        TitleManger insetance = TitleManger.getInsetance();
        insetance.setContext(this);
        insetance.setName("注册");
        initView();
        initData();
    }

    private void initData() {
            HttpUtils.GET(xHandler,MCConstant.getAboutUsUrl());
    }

    private void initView() {
        tv_toLogin = (TextView) findViewById(R.id.zj_Login);
        btn_Register = (Button) findViewById(R.id.li_Register);
        radioGroup = (RadioGroup) findViewById(R.id.id_radioGroup1);
        radioButton_phoneRegister = (RadioButton) findViewById(R.id.rb_PhoneRegister);
        radioButton_AccountRegister = (RadioButton) findViewById(R.id.rb_AccountRegister);
        login_WeChat = (ImageView) findViewById(R.id.Login_WeChat1);
        login_QQ = (ImageView) findViewById(R.id.Login_QQ1);
        join_QQqun = (ImageView) findViewById(R.id.img_JohnQun1);
        checkBox = (CheckBox) findViewById(R.id.chex);
        et_RegisterAccount = (EditText) findViewById(R.id.register_account);
        getEt_RegisterPassword = (EditText) findViewById(R.id.register_password);
        et_Code = (EditText) findViewById(R.id.et_phonemes);
        tv_GetPhoneCode = (TextView) findViewById(R.id.tv_getPhoneCode);
        tv_WangZhi = (TextView) findViewById(R.id.wangzhi1);
        tv_XieYi = (TextView) findViewById(R.id.tiaokuan);
        tv_QunNum = (TextView) findViewById(R.id.qunhao1);
        tv_appText = (TextView) findViewById(R.id.AppText1);
        img_GetSuiJiCode = (ImageView) findViewById(R.id.tv_getSuiJiCode);

        img_GetSuiJiCode.setImageBitmap(Autjcode.getInstance().createBitmap());
        code_resh = Autjcode.getInstance().getCode().toLowerCase();
        img_GetSuiJiCode.setOnClickListener(this);
        btn_Register.setOnClickListener(this);
        tv_GetPhoneCode.setOnClickListener(this);
        tv_XieYi.setOnClickListener(this);
        login_WeChat.setOnClickListener(this);
        login_QQ.setOnClickListener(this);
        join_QQqun.setOnClickListener(this);
        tv_WangZhi.setOnClickListener(this);
        tv_toLogin.setOnClickListener(this);
        radioGroup.setOnCheckedChangeListener(onCheckedChangeListener);
    }

    RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.rb_PhoneRegister) {
                clearText();
                et_RegisterAccount.setEnabled(true);
                tv_GetPhoneCode.setVisibility(View.VISIBLE);
                img_GetSuiJiCode.setVisibility(View.GONE);
            } else if (checkedId == R.id.rb_AccountRegister) {
                clearText();
                et_RegisterAccount.setEnabled(true);
                tv_GetPhoneCode.setVisibility(View.GONE);
                img_GetSuiJiCode.setVisibility(View.VISIBLE);
            }
        }

    };

    public void clearText() {
        if (et_RegisterAccount.getText() != null || getEt_RegisterPassword.getText() != null || et_Code.getText() != null) {
            et_RegisterAccount.getText().clear();
            getEt_RegisterPassword.getText().clear();
            et_Code.getText().clear();
        }
    }

    @Override
    public void onClick(View v) {
        register_Account = et_RegisterAccount.getText().toString();
        register_Password = getEt_RegisterPassword.getText().toString();
        register_Code = et_Code.getText().toString();

        if (v.getId() == R.id.tv_getSuiJiCode) {
            img_GetSuiJiCode.setImageBitmap(Autjcode.getInstance().createBitmap());
            code_resh = Autjcode.getInstance().getCode().toLowerCase();
        }
        if (v.getId() == R.id.tv_getPhoneCode) {
            if (MCUtils.isMobileNO(register_Account) == true) {
                et_RegisterAccount.setEnabled(false);
                TimeCount time = new TimeCount(60000, 1000);// 构造CountDownTimer对象
                time.start();// 开始计时
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("phone", register_Account);
                    HttpUtils.POST(mHandler, MCConstant.getUserGetPhoneCodeUrl(), jsonObject.toString(), true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                ToastUtil.showToast("输入账号不合法");
            }
        }
        if (v.getId() == R.id.li_Register) {
            if (checkBox.isChecked()) {
                if (radioButton_phoneRegister.isChecked() == true) {
                    if (MCUtils.isMobileNO(register_Account) == true && register_Password.length() >= 6&&register_Code!=null) {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("account", register_Account);
                            jsonObject.put("password", register_Password);
                            jsonObject.put("code",register_Code);
                            HttpUtils.POST(rHandler, MCConstant.getUserPhoneRegisterUrl(), jsonObject.toString(), true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if(register_Code.isEmpty()){
                        ToastUtil.showToast("短信验证码输入有误");
                    }else if (MCUtils.isMobileNO(register_Account) == false) {
                        ToastUtil.showToast("检查手机号输入是否正确");
                    } else if (register_Password.length() < 6) {
                        ToastUtil.showToast("密码长度不应小于六位");
                    }
                }
                if (radioButton_AccountRegister.isChecked() == true) {      //普通账号注册
                    if (register_Account.length()>=6 && register_Password.length() >= 6) {
                        if (register_Code.toLowerCase().equals(code_resh)) {//输入验证码等于随机验证码
                            try {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("account", register_Account);
                                jsonObject.put("password", register_Password);
                                HttpUtils.POST(rHandler, MCConstant.getUserRegisterUrl(), jsonObject.toString(), true);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showToast("验证码输入有误");
                        }
                    } else if (register_Account.length()<6 ) {
                        ToastUtil.showToast("账号长度不得小于六位");
                    } else if (register_Password.length() < 6) {
                        ToastUtil.showToast("密码长度不得小于六位");
                    }
                }}else {
                ToastUtil.showToast("请阅读条款");
            }
        }
        if (v.getId() == R.id.tiaokuan) {
            if(!TextUtils.isEmpty(aboutUs.xyUrl)){
                Intent intent=new Intent();
                intent.putExtra("url",aboutUs.xyUrl);
                intent.putExtra("title","注册协议");
                intent.setClass(RegisterActivity.this,AgreementActivity.class);
                startActivity(intent);
                finish();
            }else{
                ToastUtil.showToast("协议链接为空");
            }
        }
        if (v.getId() == R.id.Login_WeChat1) {
            MCThirdPartyLogin.getInstance().toLogin(RegisterActivity.this, MCThird.Wechat,new Primary(RegisterActivity.this,"wx"));
        }
        if (v.getId() == R.id.Login_QQ1) {
            MCThirdPartyLogin.getInstance().toLogin(RegisterActivity.this, MCThird.QQ,new Primary(RegisterActivity.this,"qq"));
        }
        if (v.getId() == R.id.img_JohnQun1) {
                MCUtils.joinQQGroup(RegisterActivity.this,aboutUs.qunKey);
        }
        if (v.getId() == R.id.zj_Login) {
            startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
            finish();
        }
        if (v.getId() == R.id.wangzhi1) {
            if(!TextUtils.isEmpty(aboutUs.gNet)){
                Intent intent=new Intent();
                intent.putExtra("url",aboutUs.gNet);
                intent.putExtra("title","官网");
                intent.setClass(RegisterActivity.this,AgreementActivity.class);
                startActivity(intent);
                finish();
            }else{
                ToastUtil.showToast("官网链接为空");
            }
        }

    }

    // /* 定义一个倒计时的内部类 */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // 计时过程显示
            tv_GetPhoneCode.setClickable(false);
            tv_GetPhoneCode.setText(millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            tv_GetPhoneCode.setText("重新验证");
            tv_GetPhoneCode.setClickable(true);
            tv_GetPhoneCode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TimeCount time = new TimeCount(60000, 1000);// 构造CountDownTimer对象
                    time.start();// 开始计时
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("phone", register_Account);
                         HttpUtils.POST(mHandler, MCConstant.getUserGetPhoneCodeUrl(), jsonObject.toString(), true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    /**
     * 获取验证码
     */
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    boolean dnScode = Json.DNSJudge("获取短信验证码", msg.obj.toString());
                    if (dnScode == true) {
                        ToastUtil.showToast("验证码获取成功");
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;
            }
        }
    };

    /**
     * 手机号、普通账号注册
     */
    Handler rHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    boolean dnScode = Json.DNSJudge("用户注册", msg.obj.toString());
                    if (dnScode == true) {
                        ToastUtil.showToast("注册成功,请登录！");
                        startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                        finish();
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;
            }
        }
    };

    /**
     * 注册界面信息  协议链接地址  QQ群Key QQ群号  APP简介  官网地址
     */
    Handler xHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    aboutUs = Json.aboutUs(msg.obj.toString());
                    if (aboutUs != null) {
                        tv_QunNum.setText(aboutUs.qunNum);
                        tv_WangZhi.setText(aboutUs.gNet);
                        tv_appText.setText(aboutUs.jianJie);
                    } else {
                        ToastUtil.showToast("关于我们为空");
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;
            }
        }
    };


}
